import 'package:bruno/bruno.dart';
import 'package:common/common.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../app_config/api_constants.dart';
import '../../../common/keep_alive_wrapper.dart';
import '../../../global_web/global_web_page.dart';
import '../../../theme/font.dart';
import '../audio_card/container_tab_indicator.dart';
import '../setting/feekback_page/feekback_view.dart';
import 'kefu_config.dart';

/// @description:
/// @author
/// @date: 2023-11-24 15:12:22
class KeFuMainPage extends StatefulWidget {
  const KeFuMainPage({Key? key}) : super(key: key);

  @override
  State<KeFuMainPage> createState() => _KeFuMainPageState();
}

class _KeFuMainPageState extends State<KeFuMainPage> with TickerProviderStateMixin {
  late TabController _tabController;
  final List<Widget> _pages = [];

  final List<String> _tabs = [];

  KeFuConfigData? keFuConfigConfig;
  List<HelpCateItem>? helpCateItems;
  @override
  void initState() {
    super.initState();

    fetchHelpIndexConfig();
    fetchHelpCateConfig();
  }

  void fetchHelpIndexConfig() {
    HttpProvider.get('/help/helpIndex', explain: '系统客服首页', success: (result) {
      KeFuConfigData config = KeFuConfigData.fromJson(result.data);
      keFuConfigConfig = config;
      setState(() {});
    });
  }

  void fetchHelpCateConfig() {
    HttpProvider.get(
      '/help/helpCate',
      explain: '获取帮助分类',
      success: (result) {
        if (result.data["data"] is List) {
          helpCateItems = result.data["data"] == null
              ? null
              : (result.data["data"] as List).map((e) => HelpCateItem.fromJson(e)).toList();
        }
        for (HelpCateItem element in helpCateItems!) {
          _tabs.add(element.cateName!);
          _pages.add(KefuListPage(key: PageStorageKey(element.cateName), item: element));
        }
        _tabController = TabController(length: _pages.length, vsync: this);
        setState(() {});
      },
      failure: (result) {
        helpCateItems = [];
        setState(() {});
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return KeepAliveWrapper(
      child: Stack(
        children: [
          Scaffold(
            backgroundColor: const Color(0xFFF6F6F6),
            appBar: BrnAppBar(title: '系统客服'),
            body: helpCateItems == null
                ? const Center(child: CupertinoActivityIndicator())
                : Column(
                    children: [
                      _tabbarWarpper(),
                      Expanded(
                        child: TabBarView(
                            controller: _tabController,
                            children: _pages.map((e) {
                              return e;
                            }).toList()),
                      ),
                    ],
                  ),
            bottomNavigationBar: keFuConfigConfig == null
                ? const SizedBox()
                : Container(
                    color: Colors.white,
                    height: 60 + AppScreen.safeAreaPaddingBottom,
                    child: Container(
                      padding:
                          EdgeInsets.only(left: 20.w, right: 20.w, top: 15, bottom: AppScreen.safeAreaPaddingBottom),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () {},
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Image.asset('assets/app/images/mine/kefu_icon.png', width: 16.w),
                                const SizedBox(width: 10),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Text(keFuConfigConfig?.title ?? '人工客服',
                                        style: TextStyle(
                                            color: const Color(0xFF000000),
                                            fontSize: 14.sp,
                                            fontWeight: FontWeight.w600)),
                                    Text(keFuConfigConfig?.desc ?? '9:00 - 18:00',
                                        style: TextStyle(color: const Color(0xFF000000), fontSize: 12.sp))
                                  ],
                                )
                              ],
                            ),
                          ),
                          Container(color: const Color(0xFFEEEEEE), height: 30, width: 1),
                          GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () {
                              Get.to(FeekbackPage());
                            },
                            child: Row(
                              children: [
                                Image.asset('assets/app/images/mine/feekback_icon.png', width: 16.w),
                                const SizedBox(width: 10),
                                Text('意见反馈',
                                    style: TextStyle(
                                        color: const Color(0xFF000000), fontSize: 14.sp, fontWeight: FontWeight.w600))
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
          ),
        ],
      ),
    );
  }

  Widget _tabbarWarpper() {
    return DefaultTabController(
      length: _pages.length,
      child: Container(
        color: Colors.white,
        // height: 40,
        alignment: Alignment.centerLeft,
        child: TabBar(
          tabAlignment: TabAlignment.start,
          controller: _tabController,
          labelColor: const Color(0xFF222222),
          indicatorColor: Colors.black,
          unselectedLabelColor: const Color(0xFF222222),
          isScrollable: true,
          indicatorWeight: 0,
          overlayColor: WidgetStateProperty.resolveWith((states) {
            return Colors.transparent;
          }),
          dividerHeight: 0,
          indicator: ContainerTabIndicator(
              color: const Color(0xFF22F2EB),
              width: 30.w,
              height: 3.w,
              radius: const BorderRadius.all(Radius.circular(14.0)),
              padding: const EdgeInsets.only(left: 0.0, right: 0, top: 15, bottom: 0)),
          labelStyle: const TextStyle(color: Color(0xFF22F2EB), fontSize: 15, fontWeight: AppFontWeight.semiBold),
          unselectedLabelStyle: const TextStyle(color: Color(0xFF222222), fontSize: 15),
          onTap: (index) {
            logs(index);
          },
          tabs: List.generate(_tabs.length, (index) {
            // return Tab(text: _tabs[index]);
            return Tab(child: Text(_tabs[index]));
          }),
        ),
      ),
    );
  }
}

class KefuListPage extends StatefulWidget {
  const KefuListPage({super.key, required this.item});
  final HelpCateItem item;

  @override
  State<KefuListPage> createState() => _KefuListPageState();
}

class _KefuListPageState extends State<KefuListPage> {
  void fetchHelListConfig() {
    HttpProvider.get('/help/helpList',
        params: {
          'cateId': widget.item.id!,
          'page': 1,
          'limit': 10,
        },
        explain: '系统客服首页', success: (result) {
      KeFuConfigData config = KeFuConfigData.fromJson(result.data);

      setState(() {});
    });
  }

  @override
  void initState() {
    fetchHelListConfig();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      // color: Colors.white,
      margin: const EdgeInsets.only(top: 10),
      child: ListView.builder(
        padding: const EdgeInsets.symmetric(horizontal: 15),
        itemBuilder: (BuildContext cxt, int index) {
          return _buildItem(title: '为什么我的账号登录不了，显示被封禁。为什么我的账号登录不了，显示被封禁。', top: index == 0, bottom: index == 4);
        },
        itemCount: 5,
      ),
    );
  }

  Widget _buildItem({required String title, required bool top, required bool bottom}) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        GlobalWebPage.startInstance(title, ApiConstants.privacyPolicyUrl);
      },
      child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: top ? const Radius.circular(8) : const Radius.circular(0),
              topRight: top ? const Radius.circular(8) : const Radius.circular(0),
              bottomLeft: bottom ? const Radius.circular(8) : const Radius.circular(0),
              bottomRight: bottom ? const Radius.circular(8) : const Radius.circular(0),
            ),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 15),
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.symmetric(vertical: 15),
                color: Colors.white,
                child: Row(
                  children: [
                    Expanded(
                        child: Text(title,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(fontSize: 14.sp, color: Colors.black, fontWeight: FontWeight.w500))),
                    // const Spacer(),
                    const Icon(Icons.navigate_next_sharp, size: 20, color: Color(0xFF000000))
                  ],
                ),
              ),
              bottom ? const SizedBox() : const Divider(color: Color(0xFFEEEEEE), height: 0.5, indent: 5, endIndent: 5)
            ],
          )),
    );
  }
}
